package cn.rebeater.navigationclient.ui.dashboard;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.rebeater.navigationclient.R;


public class DashboardFragment extends Fragment {

    static Marker marker = null;
    static private MapView amapView;
    static private AMap amap;
    private final String TAG = "mydebug DashboardFragment";
    CoordinateConverter converter;
    private DashboardViewModel dashboardViewModel;
    private LatLng pos_pre_GCJ02 = null;
    private boolean flag_auto_follow = false;

    //    private AMap
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView: ");
        dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
//        final TextView textView = root.findViewById(R.id.text_dashboard);
        getParentFragmentManager().setFragmentResultListener("requestKeyForMap", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String key, @NonNull Bundle bundle) {
                double[] result = bundle.getDoubleArray("bundleKey");
                dashboardViewModel.addPosition(new NavigationData(result));
            }
        });
        setHasOptionsMenu(true);
        amapView = root.findViewById(R.id.main_map);
        amapView.onCreate(savedInstanceState);
        if (amap == null) {
            amap = amapView.getMap();
        }
        initMap();
        /*初始化坐标转换器，将WGS84坐标转换为GCJ02坐标显示在地图上*/
        converter = new CoordinateConverter(getContext());
        converter.from(CoordinateConverter.CoordType.GPS);
        dashboardViewModel.getNav().observe(getViewLifecycleOwner(), new Observer<NavigationData>() {
            @Override
            public void onChanged(@Nullable NavigationData s) {
                if (null != s)
                    showMarkerOnMap(s);
            }
        });

        return root;
    }

    void initMap() {
        LatLng latLng = new LatLng(39.906901, 116.397972);

        marker = amap.addMarker(new MarkerOptions().position(latLng).title("Robot")
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.up_marker))).setFlat(true));

        UiSettings ui = amap.getUiSettings();
        ui.setZoomControlsEnabled(false);/**/
        ui.setCompassEnabled(true);
        ui.setMyLocationButtonEnabled(false);
        ui.setZoomGesturesEnabled(true);
        ui.setRotateGesturesEnabled(false);
        ui.setTiltGesturesEnabled(true);

/*        amap.setMyLocationEnabled(true);
        amap.setLocationSource(new LocationSource() {
            @Override
            public void activate(OnLocationChangedListener onLocationChangedListener) {

            }

            @Override
            public void deactivate() {

            }
        });*/
    }

    void showMarkerOnMap(LatLng pos_GPS, float yaw, int color) {
        converter.coord(pos_GPS);
        LatLng pos = converter.convert();
        marker.setPosition(pos);
        yaw = yaw < 0 ? 360 + yaw : yaw;
        marker.setRotateAngle(yaw);
        List<LatLng> latLngs = new ArrayList<>();
        if (pos_pre_GCJ02 != null) {
            latLngs.add(pos_pre_GCJ02);
            latLngs.add(pos);
            amap.addPolyline(new PolylineOptions().
                    addAll(latLngs).width(10).color(color));
        }
        if (flag_auto_follow) {
            //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
            CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(pos, 18, 0, 0));
            amap.moveCamera(mCameraUpdate);
        }
        pos_pre_GCJ02 = pos;
    }

    void showMarkerOnMap(NavigationData nav) {
        LatLng latLng = new LatLng(nav.lat, nav.lon);
        int color = Color.argb(255, 23, 85, 24);
        ;
        switch (nav.mode) {
            case 1:
                color = Color.argb(255, 200, 172, 1);
                break;
            case 2:
                color = Color.argb(255, 100, 172, 254);
            case 3:
                break;
            case 4:
                color = Color.argb(255, 1, 254, 1);
                break;
            case 5:
                color = Color.argb(255, 1, 254, 125);
                break;
            case 6:
                color = Color.argb(255, 55, 55, 55);
            default:
                break;

        }
        showMarkerOnMap(latLng, (float) (-nav.heading), color);

    }

//    void showResultOnAmap(String result) {
//        double[] pvts = ne w double[11];
//        int i;
//        String[] strings = result.split(",");
//        if (strings.length < 11) {
//            return;
//        }
//        if (strings[0].equals("POS")) {
//            for (i = 1; i < 11; i++)
//                pvts[i - 1] = Double.parseDouble(strings[i]);
//        }
//        showMarkerOnMap(new LatLng(pvts[1], pvts[2]), (float) pvts[9]);
//    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        amapView.onResume();
    }

    @Override
    public void onPause() {
        Log.i(TAG, "onPause: ");
        super.onPause();
        amapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        Log.i(TAG, "onSaveInstanceState: ");
        amapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        amapView.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.clear_record:
                if (amap != null) {
                    amap.clear();
                    if (pos_pre_GCJ02 != null) {
                        marker = amap.addMarker(new MarkerOptions().position(pos_pre_GCJ02).title("Robot")
                                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.up_marker))).setFlat(true));
                    }
                }
                break;
            case R.id.camera_auto_follow:
                flag_auto_follow = !flag_auto_follow;
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main_pop_menu, menu);
    }
}